<!--
*@Author: QWP
*@Description: 天气信息
*@Date: 2024-07-11 17:32:44
-->
<template>
  <a-layout class="u-weather" :class="{ 'u-card-weather': isCard }">
    <a-layout-content style="z-index: 2; overflow: auto">
      <div style="position: absolute; left: -16px; top: -16px; width: calc(100% + 32px); max-height: 300px;"
        v-if="isCard == false">
        <a-image :src="urlFile('weather/bg.png')" :preview="false" width="100%">
        </a-image>
      </div>
      <div style="margin: 0 auto; width: 70%;" :style="{ width: isCard == false ? '70%' : '100%' }">
        <a-row align="middle">
          <a-col :span="8" v-if="isCard == false">
            <span style="font-size: 26px; color: #fff;">天气信息</span>
          </a-col>
          <a-col flex="1" :align="isCard == false ? 'end' : 'start'" justify="end" class="f-w-100 u-locat-info">
            <EnvironmentOutlined style="margin-right: 10px; font-size: 20px;" />
            <a-space size="large">
              <span v-for="item in currentCitys">{{ item.cityZh }}</span>
              <a-cascader v-if="isCard == false" v-model:value="weatherCity" :options="citys" placeholder="搜索市、区、县等城市"
                showSearch defaultValue="CN101270101"
                :field-names="{ label: 'cityZh', value: 'id', children: 'children' }" change-on-select
                class="u-city-cascader" @change="cityChange" />
            </a-space>
          </a-col>
        </a-row>
        <a-row class="f-margin-t30">
          <a-col justify="center">
            <span style=" font-size: 14px; color: #FFFFFF;">天气更新时间{{ dayWeather['update_time'] ||
              dayjs().format("HH:DD") }}</span>
            <div style="position: relative">
              <span style="font-family: D-DIN, D-DIN; font-size: 86px; color: #FFFFFF;"
                :style="{ fontSize: isCard == false ? '86px' : '60px' }">{{ dayWeather['tem'] || 26 }}°</span>
              <span style="font-size: 32px; color: #FFFFFF;">{{ dayWeather['wea'] || '晴' }}</span>
              <div style="position: absolute; bottom: 26px; left: 300px;" v-if="(dayWeather.alarm || []).length != 0">
                <a-image :src="getAlarmImg(dayWeather.alarm)" :preview="false" width="44px" height="36px">
                </a-image>
                <span style="margin-left: 12px; color: #fff;">{{ getAlarmText(dayWeather.alarm) }}</span>
              </div>
            </div>
            <a-space class="u-weather-into-detial" size="large">
              <span>
                <FlagOutlined /> {{ dayWeather['win'] || '南' }} {{ dayWeather['win_speed'] || '3级' }}
              </span>
              <span>
                <BgColorsOutlined /> 湿度 {{ dayWeather['humidity'] || '50%' }}
              </span>
              <span>
                <DashboardOutlined /> 气压 {{ dayWeather['pressure'] || 703 }}hPa
              </span>
              <span>
                <EyeOutlined /> 能见度 {{ dayWeather['visibility'] || '6km' }}
              </span>
            </a-space>
          </a-col>
          <a-col flex="1" align="end" justify="end">
            <!-- <CloudOutlined style="font-size: 100px; color: #fff"/> -->
            <template v-if="dayWeather['wea_img']">
              <u-icon-font :type="whetherImgBig[dayWeather['wea_img']]" style="font-size: 100px; color: #fff" />
            </template>
          </a-col>
        </a-row>
      </div>
      <!-- 小时天气 -->
      <div style="margin: 0 auto; width: 70%; margin-top: 50px;" v-if="isCard == false">
        <u-busi-card title="24小时预报">
          <!-- extra="数据来源中国天气网" -->
          <a-row style="width: 100%; height: 150px; overflow-x: auto;" class="hide-scrolle-bar">
            <div style="width: 2400px; display: flex; flex-direction: row;" v-if="hourWeather.length != 0">
              <a-space direction="vertical" align="center" size="middle" v-for="item in hourWeather"
                style="width: 100px; height: 60px">
                <span style="font-size: 14px; color: #666666;">{{ item.hours }}</span>
                <u-icon-font :type="whetherImg[item['wea_img']]" style="font-size: 20px;" />
                <span style="font-size: 12px; color: #333333;">{{ item.win }}{{ item.win_speed }}</span>
                <span style="font-size: 16px; color: #333333;">{{ item.tem }}°</span>
              </a-space>
            </div>
            <a-row v-else justify="center" class="f-w-100">
              <a-empty />
            </a-row>
          </a-row>
        </u-busi-card>
      </div>
      <div style="margin: 12px auto 0; width: 70%;" v-if="isCard == false">
        <u-busi-card title="未来15天天气预报">
          <a-row style="width: 100%; height: 200px; overflow-x: auto;" class="hide-scrolle-bar">
            <div style="width: 2400px; display: flex; flex-direction: row;">
              <a-space direction="vertical" align="center" size="middle" v-for="item in day15Weather"
                style="width: 130px; height: 60px">
                <div>
                  <span style="font-size: 14px; color: #666666;">{{ item.dayType }}</span>
                  <span style="font-size: 14px; color: #666666;">{{ item.date }}</span>
                </div>
                <u-icon-font :type="whetherImg[item['wea_img']]" style="font-size: 20px;" />
                <span style="font-size: 14px; color: #666666;">{{ item.wea }}</span>
                <span style="font-size: 16px; color: #1890FF;">{{ item.tem_night }}°~{{ item.tem_day }}°</span>
                <span style="font-size: 16px; color: #333333;">{{ item.win || '无风' }}</span>
              </a-space>
            </div>
          </a-row>
        </u-busi-card>
      </div>
    </a-layout-content>
  </a-layout>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useLocationStore } from '@/store'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
import axios, { Axios, AxiosInstance } from 'axios'
import { citys } from './data/city.js'
import { urlFile } from '@/util/common.js';

const props = withDefaults(
  defineProps<{
    isCard?: boolean
  }>(),
  {
    isCard: false
  }
)

const emits = defineEmits(['success'])

const locationStore = useLocationStore()
const { location } = storeToRefs(locationStore)

const weatherCity = ref<string>(['CN101270100', 'CN101270101'])
onMounted(() => {
  // getCitys()
  locationStore.setLocation()
  initData()
})

// 初始化获取数据
const initData = () => {
  let weather_date = localStorage.getItem('weather_date') ? dayjs(localStorage.getItem('weather_date')) : dayjs()
  let now_date = dayjs()
  if (now_date.diff(weather_date, 'minute') > 30 || !localStorage.getItem('weather_date')) {
    getNowDayWeather('CN101270101')
    get15DayWeather('CN101270101')
  }
  else {
    dayWeather.value = JSON.parse(localStorage.getItem('dayWeather'))
    emits('success', dayWeather.value)
    hourWeather.value = JSON.parse(localStorage.getItem('hourWeather') || '[]') || []
    day15Weather.value = JSON.parse(localStorage.getItem('day15Weather'))
  }
}

// 获取预警图片
const getAlarmImg = (alarm = []) => {
  const fAlarm = alarm[0] || {}
  let alarm_type = fAlarm['alarm_type'] || ''
  let alarm_level = (fAlarm['alarm_level'] || '').replace('色', '')
  return urlFile(`weather/alarm/${alarm_type}-${alarm_level}.png`)
}

// 获取预警文字
const getAlarmText = (alarm = []) => {
  const fAlarm = alarm[0] || {}
  let alarm_type = fAlarm['alarm_type'] || ''
  let alarm_level = (fAlarm['alarm_level'] || '')
  return `${alarm_type}${alarm_level}预警`
}

// 选中的城市
const currentCitys = ref<any[]>([{ cityZh: '四川' }, { cityZh: '成都' }])
const cityChange = (value, selectedOptions) => {
  currentCitys.value = selectedOptions;
  getNowDayWeather(selectedOptions[selectedOptions.length - 1]['id'])
  get15DayWeather(selectedOptions[selectedOptions.length - 1]['id'])
}

// 创建实例
const cAxios = (baseURL?: string) => {
  const service: AxiosInstance = axios.create({
    baseURL: '',
    timeout: 10000,
    withCredentials: false
  })
  return service
}

// 创建实例
const xhr = (url, method, data = null) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
    };
    xhr.open(method, url, true);
    xhr.send(data);
  })
}

// 小时天气
interface IHourWeather {
  aqi: string,
  aqinum: string,
  hours: string,
  tem: string,
  vis: string,
  wea: string,
  wea_img: string,
  win: string,
  win_speed: string,
}
const dayWeather = ref({
  update_time: dayjs().format("HH:DD")
})
const hourWeather: Array<IHourWeather> = ref([])

const whetherImgBig = {
  qing: 'icon-a-zu219',
  yin: 'icon-a-yin-bai1',
  yu: 'icon-zhenxue-bai',
  yun: 'icon-duoyun-bai',
  bingbao: 'icon-bingbao-bai',
  wu: 'icon-wu',
  shachen: 'icon-shachenbao',
  lei: 'icon-leizhenyu-bai',
  xue: 'icon-zhongxue-bai',
}

const whetherImg = {
  qing: 'icon-a-zu219',
  yin: 'icon-yin',
  yu: 'icon-xiaoyu',
  yun: 'icon-duoyun',
  bingbao: 'icon-bingbao',
  wu: 'icon-wu',
  shachen: 'icon-shachenbao',
  lei: 'icon-leizhenyu',
  xue: 'icon-xiaoxue',
}

// 获取中国气象局的所有城市及id
const getCitys = async () => {
  cAxios().get(`/test/api/map/weather/1?t=` + Date.now())
  cAxios().get(`/test/api/now/S1003`)
    .then(res => {
    })
  // xhr(`https://weather.cma.cn/api/map/weather/1?t=`+ Date.now(), 'get')
  // xhr(`http://weather.cma.cn/api/now/S1003`, 'get')
}

// 获取当日的天气信息
const getNowDayWeather = async (cityId?: string) => {
  let lastData = {};
  if (!cityId) {
    lastData = currentCitys.value[currentCitys.value.length - 1];
    if (lastData['cansel'] == false) {
      return
    }
  }
  const params = [
    "cityid=" + cityId || lastData['id'],
    "appid=18332121",
    "appsecret=BJhsXj8p",
    "hours=1",
    "vue=1",
  ]

  cAxios().get(`http://v0.yiketianqi.com/free/v2030?${params.join('&')}`)
    .then(res => {
      if (res.status == 200) {
        dayWeather.value = res.data;
        localStorage.setItem('dayWeather', JSON.stringify(dayWeather.value || []))
        emits('success', dayWeather.value)

        let hours = res.data.hours || [];
        hours.forEach(item => {
          if (item.hours == "00:00") {
            item.hours = dayjs().add(1, 'day').format("M月D日")
          } else if (item.hours == `${dayjs().format("HH")}:00`) {
            item.hours = "现在"
          }
        })
        hourWeather.value = res.data.hours
        localStorage.setItem('hourWeather', JSON.stringify(hourWeather.value || []))
        localStorage.setItem('weather_date', dayjs().format('YYYY-MM-DD HH:mm:ss').toString())
      }
    })
}

// 获取未来15天天气
const day15Weather = ref([]);
const get15DayWeather = async (cityId?: string) => {
  let lastData = {};
  if (!cityId) {
    lastData = currentCitys.value[currentCitys.value.length - 1];
    if (lastData['cansel'] == false) {
      return
    }
  }
  const params = [
    "cityid=" + cityId || lastData['id'],
    "appid=18332121",
    "appsecret=BJhsXj8p",
    "vue=1",
  ]

  cAxios().get(`http://v1.yiketianqi.com/free/month?${params.join('&')}`)
    .then(res => {
      try {
        if (res.status == 200) {
          day15Weather.value = res.data.data.slice(1, 16)
          localStorage.setItem('day15Weather', JSON.stringify(day15Weather.value || []))
        }
      } catch (error) {}
    })
}

defineExpose({
  // 'CN101270101'
  initData,
  whetherImgBig,
  whetherImg,
  getNowDayWeather,
  get15DayWeather
})
</script>

<style lang='scss'>
.u-weather {
  position: relative;
  background-color: unset !important;
  &::before {
    content: "";
    position: absolute;
    top: -15px;
    left: -16px;
    width: calc(100% + 32px);
    height: 300px;
    background: linear-gradient(174deg, #0283FF 0%, #7FC0FF 60%, #B3DBFF 100%);
  }

  .u-weather-top {
    width: 100%;
    height: 300px;
    border-radius: 0px 0px 0px 0px;
  }

  .u-locat-info {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 16px;
    color: #FFFFFF;

    .ant-input {
      width: 300px;
      background: rgba(255, 255, 255, 0.5);
      border-radius: 25px;
    }
  }

  .u-weather-into-detial {
    font-weight: 400;
    font-size: 16px;
    color: #FFFFFF;
  }

  .u-city-cascader {
    text-align: left;
  }
}

.u-card-weather {
  background-image: url('./../../../../assets/weather/bg.png');
  background-size: cover;
  padding: 10px 10px 0;
  &::before {
    content: "";
    position: absolute;
    top: -15px;
    left: -16px;
    width: calc(100% + 32px);
    height: 240px;
    background: linear-gradient(174deg, #0283FF 0%, #7FC0FF 60%, #B3DBFF 100%);
  }
  .u-bg-img {
    max-height: unset !important;
    height: 100% !important;
  }
}
</style>